import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import { Iconify, SvgIcon } from '@/components/icon';
import { useSettings } from '@/store/settingStore';

import { ThemeLayout } from '@/types/enum';
import { AppRouteObject } from '@/types/router';
import type { ItemType } from 'antd/es/menu/interface';
import { GetProp, MenuProps } from 'antd';
type MenuItem = GetProp<MenuProps, 'items'>[number];

type BagedType = {
  path: string;
  badge: number;
};

/**
 *   routes -> menus
 */
export function useRouteToMenuBadgeFn() {
  const { t } = useTranslation();
  const { themeLayout } = useSettings();
  const routeToMenuBadgeFn = useCallback(
    (items: AppRouteObject[], badge: BagedType[] = []): MenuItem[] => {
      return items
        .filter((item) => !item.meta?.hideMenu)
        .map((item) => {
          const badgeIndex = badge.findIndex((items) => items.path === item.path);

          const menuItem: any = [];
          const { meta, children } = item;
          if (meta) {
            const { key, label, icon, disabled, suffix } = meta;
            menuItem.key = key;
            menuItem.disabled = disabled;
            menuItem.label = (
              <div
                className={`inline-flex items-center ${
                  themeLayout === ThemeLayout.Horizontal ? 'justify-start' : 'justify-between'
                } `}
              >
                <div className="inline-flex items-center ">
                  <div>{t(label)}</div>
                  {badgeIndex > -1 && badge[badgeIndex].badge > 0 && (
                    <span
                      className="ml-[30px]  flex items-center justify-center rounded-full px-[4px] !text-xs !font-font-weight-400  text-white"
                      style={{
                        background: 'linear-gradient(180deg, #FF4646 0%, #FF8F62 100%)',
                        minWidth: '16px',
                        height: '16px',
                      }}
                    >
                      {/* {badge[badgeIndex].badge} */}
                      {badge[badgeIndex].badge >= 99 ? '99' : badge[badgeIndex].badge}
                    </span>
                  )}
                </div>
                {suffix}
              </div>
            );
            if (icon) {
              if (typeof icon === 'string') {
                if (icon.startsWith('ic')) {
                  menuItem.icon = <SvgIcon icon={icon} size={24} className="ant-menu-item-icon" />;
                } else {
                  menuItem.icon = <SvgIcon icon={icon} size={24} className="ant-menu-item-icon" />;
                }
              } else {
                menuItem.icon = icon;
              }
            }
          }
          if (children) {
            menuItem.children = routeToMenuBadgeFn(children, badge);
          }
          return menuItem as ItemType;
        });
    },
    [t, themeLayout],
  );
  return routeToMenuBadgeFn;
}
